package Control;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Bean.BeanCliente;
import Bean.BeanFilme;
import Bean.BeanFilmeConsulta;
import Bean.BeanUsuario;
import Bean.BeanUsuarioConsulta;
import DAO.DAOCliente;
import DAO.DAOExceptionMelhorCinema;
import DAO.DAOFilme;
import DAO.DAOUsuario;
import Model.Cliente;
import Model.Filme;
import Model.Usuario;

public class ControladorCliente extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, Exception {

		response.setContentType("text/html;charset=ISO-8859-1");
		PrintWriter out = response.getWriter();

		try {
			String opcao = request.getParameter("opcao");
			HttpSession session = request.getSession();
			if (session == null) {
				response.sendRedirect("../AcessoAoSistema/login.jsp");
			} else {
				if (opcao != null) {

					if (opcao.equals("novo")) {
						novoCliente(request, response);
					} else {
						if (opcao.equals("salvar")) {
							salvarCliente(request, response);

						} else {
							if (opcao.equals("editar")) {
								editarCliente(request, response, session);

							} else {
								if (opcao.equals("atualizar")) {
									atualizarCliente(request, response, session);

								}
							}
						}

					}
				}
			}

		} catch (Exception e) {
			System.out.println(e.getLocalizedMessage());
		} finally {
			out.close();
		}
	}

	private void novoCliente(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		BeanCliente bCliente = new BeanCliente();
		request.setAttribute("beanCliente", bCliente);

		RequestDispatcher dispatcher = request
				.getRequestDispatcher("Clientes/gerenciarClientes.jsp");
		dispatcher.forward(request, response);

	}

	private void atualizarCliente(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception {
		DAOUsuario dao = new DAOUsuario();
		DAOCliente daoCliente = new DAOCliente();
		BeanUsuario beanLogado = (BeanUsuario) session.getAttribute("beanUsuario"); 
		Cliente vCliente = daoCliente.buscaCliente(request.getParameter("cpf"),beanLogado.getLogin());
		if (vCliente == null){

			Usuario vUsuario = dao.buscaUsuario(request.getParameter("login"), beanLogado.getCodigo());
			if (vUsuario == null){
			Usuario user = new Usuario(request.getParameter("login"), request
					.getParameter("senha"), false, request
					.getParameter("nome"), 0);
			dao = new DAOUsuario();
			user.setCodigo(dao.buscaIdUsuario(user.getLogin()));
			daoCliente = new DAOCliente();
			dao = new DAOUsuario();
			Cliente cliente = new Cliente(request.getParameter("cpf"), request
				.getParameter("nome"), request.getParameter("endereco"),
				request.getParameter("telefone"), user);
			if (!dao.atualizarUsuario(user)) {
				response.sendRedirect("AcessoAoSistema/login.jsp");
			} else if (!daoCliente.atualizarCliente(cliente)) {
				response.sendRedirect("AcessoAoSistema/login.jsp");
			} else {
				response.sendRedirect("paginaPrincipal.jsp?result=Sucesso");
			}
			} else {
				response.sendRedirect("paginaPrincipal.jsp?result=FalhaLogin");
			}
		}else {
			response.sendRedirect("paginaPrincipal.jsp?result=FalhaCPF");
			
		}
	}

	private void editarCliente(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception {
		DAOCliente dao = new DAOCliente();
		BeanUsuario beanUsuario = (BeanUsuario) session.getAttribute("beanUsuario");
		if (beanUsuario != null){
		String login =  beanUsuario.getLogin();
		Cliente cliente = dao.buscaClienteUsuario(login);
		BeanCliente bean = new BeanCliente(cliente.getCpf(), cliente.getNome(),
				cliente.getEndereco(), cliente.getTelefone(), cliente.getUser());
		request.setAttribute("beanCliente", bean);
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("Clientes/gerenciarClientes.jsp?cpf="+bean.getCpf());
		dispatcher.forward(request, response);
		} else{
			response.sendRedirect("paginaPrincipal.jsp");
		}
	}

	private void salvarCliente(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		BeanCliente bean = (BeanCliente) request.getAttribute("beanCliente");
		DAOCliente daoCliente = new DAOCliente();
		Cliente cVerificaCPF = daoCliente.buscaCliente(request.getParameter("cpf")); 
		if (cVerificaCPF == null) {
			DAOUsuario daoUser = new DAOUsuario();
			Usuario uVerificaLogin = daoUser.buscaUsuario(request.getParameter("login"));
			if (uVerificaLogin == null) {
				Usuario user = new Usuario(request.getParameter("login"), request
						.getParameter("senha"), false, request
						.getParameter("nome"), 0);
				daoUser = new DAOUsuario();
				int idUsuario = daoUser.salvarUsuario(user);
				user.setCodigo(idUsuario);
				Cliente cliente = new Cliente(request.getParameter("cpf"), request
						.getParameter("nome"), request.getParameter("endereco"),
						request.getParameter("telefone"), user);
				daoCliente = new DAOCliente();
				if (daoCliente.salvarCliente(cliente)){
					response.sendRedirect("AcessoAoSistema/login.jsp?result=Sucesso");
				}else {
					response.sendRedirect("AcessoAoSistema/login.jsp?result=Falha");
				}
			}else {
				response.sendRedirect("AcessoAoSistema/login.jsp?result=FalhaLogin");
			}
		}else {
			response.sendRedirect("AcessoAoSistema/login.jsp?result=FalhaCPF");
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception e) {
			Logger.getLogger(ControladorCliente.class.getName()).log(
					Level.SEVERE, null, e);
		}
	}

	/**
	 * response.sendRedirect("jsp/livros/cadastroLivro.jsp"); Handles the HTTP
	 * <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception e) {
			Logger.getLogger(ControladorCliente.class.getName()).log(
					Level.SEVERE, null, e);
		}
	}

	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>

}
